package com.globallogic.oopbasics.competence.io;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import com.globallogic.oopbasics.competence.container.TotalCompetence;
import com.globallogic.oopbasics.competence.entity.CompetencyValue;
import com.globallogic.oopbasics.competence.entity.Specialist;
import com.globallogic.oopbasics.competence.entity.SpecialistProfile;
import com.globallogic.oopbasics.competence.entity.SpecialityProfile;

public class CompetencyValueScanner {

	private final File fFile;

	private List<CompetencyValue> competencyValues;
	private List<Specialist> specialists;
	private List<SpecialityProfile> specialityProfiles;
	private TotalCompetence competenciesList;
	private List<SpecialistProfile> specialistProfiles;

	public List<SpecialistProfile> getSpecialistProfiles() {
		return specialistProfiles;
	}

	/** Template method that calls {@link #processLine(String)}. */
	public final void processLineByLine() throws FileNotFoundException {
		Scanner scanner = new Scanner(new FileReader(fFile));
		try {
			while (scanner.hasNextLine()) {
				processLine(scanner.nextLine());
			}
		} finally {
			scanner.close();
		}
	}

	public CompetencyValueScanner(String aFileName,
			List<Specialist> specialists,
			List<SpecialityProfile> specialityProfiles,
			TotalCompetence competenciesList) throws FileNotFoundException {
		this.competenciesList = competenciesList;
		this.specialists = specialists;
		this.specialityProfiles = specialityProfiles;
		init();
		fFile = new File(aFileName);
		processLineByLine();
	}

	protected void init() {
		specialistProfiles = new ArrayList<SpecialistProfile>();
	}

	protected void processLine(String aLine) {
		// use a second Scanner to parse the content of each line
		Scanner scanner = new Scanner(aLine);
		scanner.useDelimiter("~");
		int specialistId = scanner.nextInt();
		int specialityId = scanner.nextInt();

		competencyValues = new ArrayList<CompetencyValue>();
		while (scanner.hasNext()) {

			int competencyId = scanner.nextInt();
			double competencyValue = scanner.nextDouble();
			competencyValues.add(new CompetencyValue(competenciesList
					.getContainer().get(competencyId - 1), competencyValue));
		}

		CompetencyValue[] competencyValuesTemp = new CompetencyValue[competencyValues
				.size()];

		for (int i = 0; i < competencyValues.size(); i++) {
			competencyValuesTemp[i] = competencyValues.get(i);
		}

		if (specialists.size() > 0 && specialityProfiles.size() > 0) {
			specialistProfiles.add(new SpecialistProfile(specialists
					.get(specialistId - 1), specialityProfiles
					.get(specialityId - 1), competencyValuesTemp));
		}
	}

}
